from bitcoin.core.script import *

from utils import *
from config import (my_private_key, my_public_key, my_address,
                    faucet_address)


def P2PKH_scriptPubKey(address):    #对公钥和签名加密检查，确保有效，验证输入的合法性
    ######################################################################
    # TODO: Complete the standard scriptPubKey implementation for a
    # PayToPublicKeyHash transaction
    return [OP_DUP, OP_HASH160, address, OP_EQUALVERIFY, OP_CHECKSIG]   #OP_DUP是公钥，OP_HASH160是哈希公钥，address是接收方哈希公钥，OP_EQUALVERIFY检查公钥是否匹配，OP_CHECKSIG检查公钥和签名是否匹配
    ######################################################################


def P2PKH_scriptSig(txin, txout, txin_scriptPubKey):
    signature = create_OP_CHECKSIG_signature(txin, txout, txin_scriptPubKey,
                                             my_private_key)    #生成签名
    ######################################################################
    # TODO: Complete this script to unlock the BTC that was sent to you
    # in the PayToPublicKeyHash transaction. You may need to use variables
    # that are globally defined.
    return [signature, my_public_key]   #有签名有公钥，解锁比特币
    ######################################################################


def send_from_P2PKH_transaction(amount_to_send, txid_to_spend, utxo_index,
                                txout_scriptPubKey):
    txout = create_txout(amount_to_send, txout_scriptPubKey)    #创建输出

    txin_scriptPubKey = P2PKH_scriptPubKey(my_address)  #获取输入脚本，验证当前输入的合法性
    txin = create_txin(txid_to_spend, utxo_index)   #创建输入
    txin_scriptSig = P2PKH_scriptSig(txin, txout, txin_scriptPubKey)    #创建签名脚本

    new_tx = create_signed_transaction(txin, txout, txin_scriptPubKey,
                                       txin_scriptSig)  #创建新交易:

    return broadcast_transaction(new_tx)    #将新创建的交易发送到比特币网络


if __name__ == '__main__':
    ######################################################################
    # TODO: set these parameters correctly
    amount_to_send = 0.000001   #要从上一笔分10份钱交易里花多少钱
    txid_to_spend = (
        '4e506e7540ec8931641112b53b74e4fa1f51aa1d00d41e12bba5dd0afcc047ca') #上一笔分10份钱的交易ID，作为这次花的输入
    utxo_index =0
    ######################################################################

    txout_scriptPubKey = P2PKH_scriptPubKey(faucet_address)
    response = send_from_P2PKH_transaction(
        amount_to_send, txid_to_spend, utxo_index, txout_scriptPubKey)
    print(response.status_code, response.reason)
    print(response.text)
